//package com.example.wm.utils;
//
//import ch.qos.logback.classic.Level;
//import ch.qos.logback.classic.LoggerContext;
//import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
//import ch.qos.logback.classic.spi.ILoggingEvent;
//import ch.qos.logback.classic.Logger;
//import ch.qos.logback.core.FileAppender;
//import org.slf4j.LoggerFactory;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//
//import java.util.Map;
//import java.util.Set;
//import java.util.concurrent.ConcurrentHashMap;
//
//@Component
//public class ThreadMonitorScheduler {
//
//    private static final Logger logger = (Logger) LoggerFactory.getLogger(ThreadMonitorScheduler.class);
//    private final Map<Thread, Long> threadStateMap = new ConcurrentHashMap<>();
//
//    @Scheduled(fixedRate = 1000) // 每隔1秒检查一次
//    public void checkThreadStates() {
//        // 获取所有活跃线程
//        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
//        for (Thread thread : threadSet) {
//            long previousStateTime = threadStateMap.getOrDefault(thread, 0L);
//            long currentStateTime = System.currentTimeMillis();
//
//            // 检查线程是否处于阻塞状态
//            if (thread.getState() == Thread.State.BLOCKED || thread.getState() == Thread.State.WAITING || thread.getState() == Thread.State.TIMED_WAITING) {
//                if (currentStateTime - previousStateTime >= 1000) { // 如果阻塞超过1秒
//                    logger.warn("检测到线程 {} 位于阻塞状态超过1秒", thread.getName());
////                    createBlockingLogFile(thread);
//
//                    // 设置一个新的上下文
//                    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
//                    Logger blockingLogger = loggerContext.getLogger("blockingLogger");
//
//                    // 记录堆栈跟踪信息到日志文件
//                    recordStackTrace(thread, blockingLogger);
//                }
//            } else {
//                threadStateMap.put(thread, currentStateTime);
//            }
//        }
//    }
//
//    private void createBlockingLogFile(Thread thread) {
//        String timestamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
//        String logFilePath = "logs/blocking-" + timestamp + "-" + thread.getName() + ".log";
//
//        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
//        Logger blockingLogger = loggerContext.getLogger("blockingLogger");
//
//        // 检查是否已经存在 appender，如果存在则移除
//        if (blockingLogger.getAppender("FILE_APPENDER") != null) {
//            blockingLogger.detachAppender("FILE_APPENDER");
//        }
//
//        // 创建一个新的 FileAppender
//        FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
//        fileAppender.setContext(loggerContext);
//        fileAppender.setName("FILE_APPENDER");
//        fileAppender.setFile(logFilePath);
//        fileAppender.setAppend(false);
//
//        // 设置编码器
//        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
//        encoder.setContext(loggerContext);
//        encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss} %-5level %thread %logger{36} - %msg%n");
//        encoder.start();
//
//        fileAppender.setEncoder(encoder);
//        fileAppender.start();
//        blockingLogger.addAppender(fileAppender);
//        blockingLogger.setLevel(Level.ERROR);
//        blockingLogger.setAdditive(false);
//
//        // 记录日志
//        blockingLogger.info("创建了新的阻塞日志文件: {}", logFilePath);
//
//    }
//
//    private void recordStackTrace(Thread thread, Logger blockingLogger) {
//        blockingLogger.warn("线程 {} 阻塞堆栈跟踪信息:", thread.getName());
//        for (StackTraceElement element : thread.getStackTrace()) {
//            blockingLogger.debug("堆栈跟踪: {}", element);
//        }
//    }
//}